
from datetime import datetime

from bson import ObjectId
from fastapi import APIRouter
from pydantic import BaseModel,Field
from typing import List, Optional
from core.config import mongo_engine, response_body
from core.mongo_utils import make_ids_str,make_id_str
router = APIRouter(prefix='/book')
mongo_client=mongo_engine["tools-simon"]
book_collection=mongo_client['book']


class BookUrlModel(BaseModel):
    douban_home: str=None
    dedao_home: str=None
    dedao_listen_home: str=None

# 添加书籍
class BookInfoModel(BaseModel):
    id: Optional[str] = Field(default=None, alias="_id")
    name: str
    author: str
    cover: str
    publisher: str=None
    publish_time: str=None
    isbn: str=None
    word_count: int=None
    summary: str=None
    urls: BookUrlModel=None
    model_config = {"populate_by_name": True}

"""
# 接收前端数据
data = {"_id": "507f1f77bcf86cd799439011", "name": "test"}
item = ItemModel(**data)
print(item.id)  # '507f1f77bcf86cd799439011' （字符串）

# 返回给前端
print(item.model_dump(by_alias=True))
# {'_id': '507f1f77bcf86cd799439011', 'name': 'test'}
"""

# 添加&更新书籍
@router.post("/add_book", summary="添加书籍")
async def add_book_info(book: BookInfoModel):
    """
    添加书籍,如果数据有id,则更新书籍信息
    :param book: 书籍信息
    :return: 书籍信息
    """
    book_info=book.model_dump(exclude={"id"})
    if book.id is not None:
        # 🔁 更新
        book_info['update_at']=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        res=book_collection.update_one({'_id':ObjectId(book.id)},{'$set':book_info})
        if res.modified_count == 0:
            response_body['msg']='更新书籍失败'
            response_body['data'] = None
        else:
            response_body['msg']='更新书籍成功'
            response_body['data'] = {'_id':str(book.id)}
    else:
        # 添加
        book_info['update_at']=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        res=book_collection.insert_one(book_info)
        if res.inserted_id is None:
            response_body['msg']='添加书籍失败'
            response_body['data'] = None
        else:
            response_body['msg']='添加书籍成功'
            response_body['data'] = {'_id':str(res.inserted_id)}
    return response_body
        
# 根据id获取书籍
@router.get("/get_book_by_id", summary="根据id获取书籍")
async def get_book_by_id(book_id: str):
    """
    根据id获取书籍
    :param book_id: 书籍id
    :return: 书籍信息
    """
    book_info=book_collection.find_one({'_id':ObjectId(book_id)})
    if book_info is None:
        response_body['msg']='书籍不存在'
        response_body['data'] = None
    else:
        response_body['msg']='获取书籍成功'
        response_body['data'] = make_id_str(book_info)
    return response_body


# // curl -X 'GET' \
# //   'http://127.0.0.1:8000/api/v1/media/book/get_book_list/?page=1&page_size=10&query=元' \
# //   -H 'accept: application/json'

@router.get("/get_book_list", summary="分页获取书籍")
async def get_book_list(page: int=1, page_size: int=10, query: str='',activate: bool=None):
    """
    分页获取书籍
    :param page: 页码
    :param page_size: 每页数量
    :param query: 搜索关键词
    :return: 书籍列表
    """
    skip=(page-1)*page_size
    if len(query.strip()) == 0:
       
        book_list=book_collection.find({}).skip(skip).limit(page_size)
    else:
        if activate is None:
            
            book_list=book_collection.find({'name':{'$regex':query},'author':{'$regex':query},
        'summary':{'$regex':query}}).skip(skip).limit(page_size)

        else:
            book_list=book_collection.find({'name':{'$regex':query},'author':{'$regex':query},
            'summary':{'$regex':query},
            'activate':activate}).skip(skip).limit(page_size)
    book_list=list(book_list)
    response_body['msg']='获取书籍成功'
    response_body['data'] = {'total':book_collection.count_documents({}),'list':make_ids_str(book_list)}
    return response_body

# 删除激活书籍切换
@router.get("/delete_book", summary="删除书籍")
async def delete_book(book_id: str):
    """
    删除书籍
    :param book_id: 书籍id
    :return: 书籍信息
    """
    # 修改activate为false或者true去反
    try:
        # 针对有activate状态的书籍
        res_activate=book_collection.update_one({'_id':ObjectId(book_id)},{'$set':{'activate':not book_collection.find_one({'_id':ObjectId(book_id)})['activate']}})
        print(type(res_activate.modified_count))
        response_body['msg']='切换书籍状态成功'+('删除' if res_activate.modified_count else '激活')
        response_body['data'] = {'id':book_id,'activate':res_activate.modified_count}
    except Exception as e:
        # 针对没有activate状态的书籍
        res_activate=book_collection.update_one({'_id':ObjectId(book_id)},{'$set':{'activate':True}})
        print(res_activate.modified_count)
        response_body['msg']='书籍默认无状态，现已激活'
        response_body['data'] = {'id':book_id,'activate':res_activate.modified_count}
    return response_body


data={
    "book_id": 0,
    "name": "元朝理财记：从成吉思汗的崛起到元朝的衰亡",
    "author": "郭建龙",
    "cover":"https://piccdn2.umiwi.com/uploader/image/cms_ebook/2025010321/1863920446378874216/010321.jpeg?x-oss-process=image/resize,m_fill,h_320,w_240",
    "publisher": "中信出版社·读客文化",
    "publish_time": "2024-12-01",
    "isbn": "9787521767117",
    "word_count": 203,
    "summary": "元朝，这个统一了中国全境、结束了隋唐以来的南北对峙与多政权并列割据局面的强大王朝，只存在了短短的一百余年，这到底是为什么呢？",
    "urls": {
        "douban_home": "https://www.douban.com/people/132423243/",
        "dedao_home":
            "https://www.dedao.cn/ebook/detail?id=nroX7MYDaKMjy7eNqrmOX6pnAQ5Vg04qm2OWJzxbE9LZl1o8RkGd2BPYv4x6d9me",
        "dedao_listen_home": ""
    }
}